import { createRoot, Root } from "react-dom/client";
import React, { useState } from "react";

export class ReactComponent {

	private readonly root: Root;
	public propsState: { [key in string]: { set: (v: any) => void } } = {};

	constructor(container: HTMLDivElement, component: React.FC<any>, props?: {
		[key in string]: {
			value: any,
			state?: boolean,
		}
	}) {
		const content = () => {
			const propsValue: { [key in string]: any } = {};
			if (props != null) {
				for (let key in props) {
					if (props[key].state) {
						const [value, setValue] = useState<any>(props[key].value);
						propsValue[key] = value;
						this.propsState[key] = { set: setValue };
					} else {
						propsValue[key] = props[key].value;
					}
				}
			}
			return (<>{React.createElement(component, propsValue)}</>);
		}
		this.root = createRoot(container);
		this.root.render(React.createElement(content));
	}

	public destroy(): void {
		this.root.unmount();
	}

}
